import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Row, Col, Card, Spin, Pagination, Empty, Slider, Checkbox, Radio, Space, Button } from 'antd';
import styled from 'styled-components';
import MainLayout from '../../components/Layout/MainLayout';
import HotelCard from '../../components/HotelCard';
import SearchBox from '../../components/SearchBox';
import { searchHotels } from '../../api/hotelApi';
import { Hotel } from '../../api/types';
import moment from 'moment';

const PageContainer = styled.div`
  padding: 20px 0;
`;

const FilterCard = styled(Card)`
  margin-bottom: 20px;
`;

const FilterTitle = styled.h3`
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
`;

const FilterSection = styled.div`
  margin-bottom: 20px;
`;

const ResultsHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
`;

const ResultCount = styled.div`
  font-size: 14px;
  color: #666;
`;

const HotelListContainer = styled.div`
  margin-bottom: 20px;
`;

const PaginationContainer = styled.div`
  display: flex;
  justify-content: center;
  margin-top: 30px;
`;

// 设施选项
const facilityOptions = [
  { label: '免费Wi-Fi', value: 'wifi' },
  { label: '停车场', value: 'parking' },
  { label: '游泳池', value: 'pool' },
  { label: '健身房', value: 'gym' },
  { label: '餐厅', value: 'restaurant' },
  { label: 'spa', value: 'spa' },
  { label: '商务中心', value: 'business' },
  { label: '会议室', value: 'meeting' },
  { label: '接送服务', value: 'shuttle' }
];

const HotelListPage: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [hotels, setHotels] = useState<{
    list: Hotel[];
    total: number;
    loading: boolean;
  }>({
    list: [],
    total: 0,
    loading: true
  });

  // 筛选条件状态
  const [filters, setFilters] = useState({
    priceRange: [0, 3000],
    rating: 0,
    facilities: [] as string[]
  });

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10
  });

  // 从URL参数获取搜索条件
  const city = searchParams.get('city') || '';
  const checkInDate = searchParams.get('checkIn') || '';
  const checkOutDate = searchParams.get('checkOut') || '';
  const guests = Number(searchParams.get('guests')) || 2;

  // 获取酒店列表数据
  useEffect(() => {
    const fetchHotels = async () => {
      setHotels(prev => ({ ...prev, loading: true }));
      
      try {
        const params = {
          city,
          checkInDate,
          checkOutDate,
          guests,
          minPrice: filters.priceRange[0],
          maxPrice: filters.priceRange[1],
          rating: filters.rating || undefined,
          facilities: filters.facilities.length > 0 ? filters.facilities : undefined,
          page: pagination.current,
          pageSize: pagination.pageSize
        };
        
        const response = await searchHotels(params);
        
        setHotels({
          list: response.data.list,
          total: response.data.total,
          loading: false
        });
      } catch (error) {
        console.error('获取酒店列表失败', error);
        setHotels({
          list: [],
          total: 0,
          loading: false
        });
      }
    };
    
    fetchHotels();
  }, [city, checkInDate, checkOutDate, guests, filters, pagination.current, pagination.pageSize]);

  // 处理价格范围变化
  const handlePriceChange = (value: number | number[]) => {
    setFilters(prev => ({ ...prev, priceRange: value as [number, number] }));
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理评分变化
  const handleRatingChange = (e: any) => {
    setFilters(prev => ({ ...prev, rating: e.target.value }));
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理设施选项变化
  const handleFacilitiesChange = (checkedValues: string[]) => {
    setFilters(prev => ({ ...prev, facilities: checkedValues }));
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    setPagination({
      current: page,
      pageSize: pageSize || pagination.pageSize
    });
  };

  // 重置所有筛选条件
  const handleReset = () => {
    setFilters({
      priceRange: [0, 3000],
      rating: 0,
      facilities: []
    });
    setPagination({ current: 1, pageSize: 10 });
  };

  return (
    <MainLayout>
      <PageContainer className="container">
        <Row gutter={20}>
          <Col xs={24} sm={24} md={6} lg={6} xl={5}>
            {/* 筛选条件区域 */}
            <FilterCard title="搜索条件">
              <SearchBox initialValues={{
                destination: city,
                dateRange: checkInDate && checkOutDate ? 
                  [moment(checkInDate), moment(checkOutDate)] : undefined,
                guests: guests
              }} />
            </FilterCard>
            
            <FilterCard>
              <FilterSection>
                <FilterTitle>价格范围</FilterTitle>
                <Slider
                  range
                  min={0}
                  max={3000}
                  step={50}
                  value={filters.priceRange}
                  onChange={handlePriceChange}
                  tipFormatter={value => `¥${value}`}
                />
                <div>¥{filters.priceRange[0]} - ¥{filters.priceRange[1]}</div>
              </FilterSection>
              
              <FilterSection>
                <FilterTitle>酒店评分</FilterTitle>
                <Radio.Group onChange={handleRatingChange} value={filters.rating}>
                  <Space direction="vertical">
                    <Radio value={0}>不限</Radio>
                    <Radio value={3}>3星及以上</Radio>
                    <Radio value={4}>4星及以上</Radio>
                    <Radio value={4.5}>4.5星及以上</Radio>
                  </Space>
                </Radio.Group>
              </FilterSection>
              
              <FilterSection>
                <FilterTitle>酒店设施</FilterTitle>
                <Checkbox.Group
                  options={facilityOptions}
                  value={filters.facilities}
                  onChange={handleFacilitiesChange}
                />
              </FilterSection>
              
              <Button type="primary" onClick={handleReset} block>
                重置筛选条件
              </Button>
            </FilterCard>
          </Col>
          
          <Col xs={24} sm={24} md={18} lg={18} xl={19}>
            {/* 酒店列表区域 */}
            <Card>
              <ResultsHeader>
                <ResultCount>
                  {hotels.loading ? '正在加载...' : `为您找到 ${hotels.total} 家酒店`}
                </ResultCount>
              </ResultsHeader>
              
              <HotelListContainer>
                {hotels.loading ? (
                  <div style={{ textAlign: 'center', padding: '40px 0' }}>
                    <Spin size="large" />
                  </div>
                ) : hotels.list.length > 0 ? (
                  <Row gutter={[16, 16]}>
                    {hotels.list.map(hotel => (
                      <Col xs={24} sm={12} md={12} lg={8} xl={8} key={hotel.id}>
                        <HotelCard hotel={hotel} />
                      </Col>
                    ))}
                  </Row>
                ) : (
                  <Empty
                    description="没有找到符合条件的酒店"
                    style={{ margin: '40px 0' }}
                  />
                )}
              </HotelListContainer>
              
              {hotels.total > 0 && (
                <PaginationContainer>
                  <Pagination
                    current={pagination.current}
                    pageSize={pagination.pageSize}
                    total={hotels.total}
                    onChange={handlePageChange}
                    showSizeChanger={false}
                  />
                </PaginationContainer>
              )}
            </Card>
          </Col>
        </Row>
      </PageContainer>
    </MainLayout>
  );
};

export default HotelListPage; 